import { _decorator, Component, instantiate, Node, Vec3 } from 'cc';
import { DataManager } from 'db://assets/scripts/DataManager';
import { PalBattleHero, PalBattleSkill } from 'db://assets/scripts/PalBattleSystem';
import { SkillItem } from './SkillItem';
import { GameManager } from 'db://assets/scripts/GameManager';
import { SkillDialogController } from './SkillDialogController';
const { ccclass, property } = _decorator;

@ccclass('SkillDialog')
export class SkillDialog extends Component {
    @property(Node)
    skillContentNode: Node = null!;
    @property(Node)
    skillItemNode: Node = null!;
    @property(Node)
    targetContentNode: Node = null!;
    @property(Node)
    skillDialogControllerNode: Node = null!;

    data: {
        heroUUID: string,
        skillIDs: number[];
        skills: PalBattleSkill[];
    }
    cache: {
        originParent: Node,
        originWorldPosition: Vec3,
    }[] = [];

    setData(data: { heroUUID: string }) {
        const hero = (GameManager.instance as GameManager).palBattleSystem.getHero(data.heroUUID);
        const skillIDs = hero.saveData.skills;
        this.data = {
            heroUUID: data.heroUUID,
            skillIDs,
            skills: skillIDs.map(skillID => (DataManager.instance as DataManager).getSkill(skillID)),
        };
        const skillDialogController = this.skillDialogControllerNode.getComponent(SkillDialogController);
        skillDialogController.skillDialog = this;
        skillDialogController.init();
    }

    render() {
        const { heroUUID, skillIDs, skills } = this.data;
        this.skillContentNode.removeAllChildren();
        skills.forEach(skill => {
            const item = instantiate(this.skillItemNode);
            item.active = true;
            item.setParent(this.skillContentNode);
            const component = item.getComponent(SkillItem);
            component.setData(skill, this);
            component.render();
        });
    }

    setSkillTargets(targets: Node[]) {
        targets.forEach(targetNode => {
            const originWorldPosition = targetNode.getWorldPosition().clone();
            this.cache.push({
                originParent: targetNode.parent,
                originWorldPosition,
            });
            targetNode.setParent(this.targetContentNode);
            targetNode.setWorldPosition(originWorldPosition);
        });
    }
    restoreSkillTargets(targets: Node[]) {
        targets.forEach(targetNode => {
            const { originParent, originWorldPosition } = this.cache.shift()!;
            targetNode.setParent(originParent);
            targetNode.setWorldPosition(originWorldPosition);
        });
    }
}


